/**
 *  *2010-9-30 下午07:57:05  add 
 */
package com.base.myproject.client.busi.payment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.business.BusinessRatify;
import com.base.myproject.client.busi.ccode.CcodeSelect;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.system.SystemMessage;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.ui.BaseBusiLeftPanel;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseGridPanel;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Administrator 2010-9-30 javazgw@gmail.com
 */
public class PayMent_p extends BaseJDBCPanel implements BusinessRatify ,AsyncCallback<CommandSyncReturnObject>{
	BaseStore<BusiObject> mstore = null;
	BaseGrid<BusiObject> grid = null;
	final static String busi = SystemMessage.busi[11];
	TextField<String> busistatus = new TextField<String>();
	 Html gcodetip= new Html();
	 Button addpayitem = new Button("选择收款发票");
	 
	 int paytype ; //2 收款 1 付款 //与发票的类型值一样invoice.invoicetype
	public PayMent_p(int paytype) {
		super();
		this.paytype = paytype;
		init();
	}

	public void complete() {
		super.complete();
		 ttiratify.setText("提交确认");
		 getToolbarll().add(ttiratify);
	}

	public void init() {
		this.setWidth("920px");
		this.setAutoHeight(true);

		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 5, 0, 0));
		this.add(initWeigetx(), centerData);

		registerMainStore(getmstore());
		registerStore(getmstore());

		this.setBusino(busi);
		setdefault();
		busistatus.setFireChangeEventOnSetValue(true);
	}

	public ContentPanel initWeigetx() {
		ContentPanel panel = new ContentPanel();
		panel.setHeaderVisible(false);
		panel.setLayout(new BorderLayout());
		BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 250);
		westData.setSplit(true);
		westData.setCollapsible(true);
		westData.setMargins(new Margins(0));
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 0, 5, 0));
		panel.add(CreateLeftPanel(), westData);
		panel.add(CreateMain(), centerData);
		panel.setSize(940, 450);
		return panel;
	}

	private void setdefault() {
		getmstore().addDefault("busicode", busi);
		getmstore().addDefault("bcode", Env.getEnvbcode());
		getmstore().addDefault("busistatus", "1");
		//收付款类型
		getmstore().addDefault("paytype",paytype);
		getmstore().addDefault("createbcode",Env.getEnvbcode());
		getmstore().addDefault("createdate",new Date());
		
	}

	public ContentPanel CreateLeftPanel() {

	
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		ColumnConfig C7 = new ColumnConfig("codename", paytype==1?"付款单号":"收款单号", 80);
		columns.add(C7);
		ColumnModel cm = new ColumnModel(columns);
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("createdate");
		type.getField("createdate").setType(Date.class);
		type.addField("paydate");
		type.getField("paydate").setType(Date.class);
		type.addField("createbcode");
		type.getField("createbcode").setType(String.class);
		type.addField("paytype");
		type.getField("paytype").setType(Integer.class);
		type.addField("ccode");
		type.getField("ccode").setType(String.class);
		type.addField("busicode");
		type.addField("busistatus");
		type.addField("codename");
		StoreInfo info = new StoreInfo();
		info.setTablename("payments");
		info.setKeyname(new String[] { "icode"});
		info.setSql("select * from payments where paytype='"+paytype+"'");

		info.addBusiParams("CODENAMEPARAMS", "{D:MMdd}{-}{INC:4}");
		info.addBusiParams("CODENAMEFILTER", "1=1");
		info.addBusiParams("CODENAME", "codename");
		BaseBusiLeftPanel basbusileftpanel = new BaseBusiLeftPanel(columns,
				type, info);
	
		this.mstore = basbusileftpanel.getStore();
		basbusileftpanel.getGrid().setAutoExpandColumn("codename");
		setMaincomponent(basbusileftpanel.getGrid());
		
		return basbusileftpanel.getPanel();
	}

	Widget CreateMain() {
		VerticalPanel vpanel = new VerticalPanel();

		vpanel.add(createForm());
		ContentPanel cpanel = new ContentPanel();
		ToolBar tb = new ToolBar();
		addpayitem.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.outstore()));
		
		addpayitem.addListener(Events.Select, getListener());
		tb.add(addpayitem);
		tb.add(gcodetip);
		cpanel.setTopComponent(tb);
		cpanel.add(create_g_Grid());
		cpanel.setHeaderVisible(false);
		vpanel.add(cpanel);
		return vpanel;
	}

	BaseFormPanel form = null;

	BaseFormPanel createForm() {
		BaseFormPanel form = new BaseFormPanel(getmstore());
		TableLayout tl = new TableLayout(4);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		form.setLayout(tl);
		form.setHeaderVisible(false);

		form.add(new Label(paytype == 1 ? "付款单号" : "收款单号"), td);

		TextField<String> codename = new TextField<String>();
		codename.setName("codename");
		codename.setAllowBlank(false);
		codename.setFieldLabel(paytype == 1 ? "付款单号" : "收款单号");

		form.add(codename, td);

		form.add(new Label("部门人员:"), td);

		TextField<String> C_num2 = new TextField<String>();
		C_num2.setName("bcode");

		form.add(C_num2, td);

		form.add(new Label("ccode:"), td);
		BaseComboBoxForm<BaseModelData> ccode ;//= new BaseComboBoxForm<BaseModelData>("ccode", "cname","ccode","where ccodetype =2",true);
		CcodeSelect ccodeselect ;
		//1 付款
		if(this.paytype==1)
		{
		 ccodeselect = new CcodeSelect(2);
		}
		//2收款
		else
		{
			 ccodeselect = new CcodeSelect(1);
		}
		ccode = ccodeselect.getCcodeSelect();
		// TextField<String> ccode = new TextField<String>();
		ccode.setName("ccode");

		ccode.setFieldLabel("客户");
		form.add(ccode, td);

		form.add(new Label("创建日期:"), td);
		DateField C_data3 = new DateField();
		C_data3.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-M-d"));
		C_data3.setName("createdate");
		form.add(C_data3, td);
		form.add(new Label("收/付款日期:"), td);
		DateField C_data4 = new DateField();
		C_data4.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-M-d"));
		C_data4.setName("paydate");
		form.add(C_data4, td);
		form.add(new Label("创建人员:"), td);
		TextField<String> C_num5 = new TextField<String>();
		C_num5.setName("createbcode");
		form.add(C_num5, td);
		form.add(new Label("收付类型:"), td);
		NumberField C_num6 = new NumberField();
		C_num6.setPropertyEditorType(Integer.class);
		C_num6.setName("paytype");
		form.add(C_num6, td);
		form.add(new Label("状态:"), td);
		busistatus.setName("busistatus");
		//	busistatus.setEnabled(false);
			busistatus.setFieldLabel("状态");
			form.add(busistatus, td);
		form.inited(126);
		return form;
	};

	BaseGridPanel g_grid = null;

	Widget create_g_Grid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		// ColumnConfig C1 = new ColumnConfig("icode", "icode", 80);
		// columns.add(C1);
		// ColumnConfig C2 = new ColumnConfig("upicode", "upicode", 80);
		// columns.add(C2);
		ColumnConfig C3 = new ColumnConfig("copyicode", "发票号", 80);
		columns.add(C3);
		ColumnConfig C4 = new ColumnConfig("cgicode", "barcode", 80);
		columns.add(C4);
		ColumnConfig C5 = new ColumnConfig("cgcode", "商品名称", 80);
		columns.add(C5);
		ColumnConfig C6 = new ColumnConfig("gcode", "商品大类", 80);
		columns.add(C6);
		ColumnConfig C7 = new ColumnConfig("modeltype", "商品规格", 80);
		columns.add(C7);
		ColumnConfig qty = new ColumnConfig("qty", "数量", 120);

		NumberField qtytext = new NumberField();
		qty.setEditor(new CellEditor(qtytext));
		columns.add(qty);
		ColumnConfig qtyunit = new ColumnConfig("qtyunit", "单位", 100);
		TextField<String> qtyunittext = new TextField<String>();
		qtyunit.setEditor(new CellEditor(qtyunittext));
		columns.add(qtyunit);
		ColumnConfig C8 = new ColumnConfig("upric", "单价", 80);
		columns.add(C8);
		// ColumnConfig C9 = new ColumnConfig("paytype", "paytype", 80);
		// columns.add(C9);

		ColumnModel cm = new ColumnModel(columns);
		g_grid = new BaseGridPanel(get_g_Store(), cm,true,true){
			protected void addnewrecord() {
				addInvoice();
				
			}
		};
		cbs.setSelectionMode(SelectionMode.SINGLE);
		g_grid.getBg().setSelectionModel(cbs);
		g_grid.getBg().setSize(650, 240);
		return g_grid;
	}

	BaseStore<BusiObject> getmstore() {
		if (mstore == null) {
			createmstore();
		}
		return mstore;
	}

	BaseStore<BusiObject> createmstore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("createdate");
		type.getField("createdate").setType(Date.class);
		type.addField("paydate");
		type.getField("paydate").setType(Date.class);
		type.addField("createbcode");
		type.getField("createbcode").setType(String.class);
		type.addField("paytype");
		type.getField("paytype").setType(Integer.class);
		type.addField("ccode");
		type.getField("ccode").setType(String.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("payments");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from payments");
		// info.setParent(mainmstore);// 关联主表
		// info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		// info.setLinkparent_chile_columns(new String[] { "upicode" });//
		// 关联主表字段
		mstore = new BaseStore<BusiObject>(type, info);
		return mstore;
	}

	BaseStore<BusiObject> g_store = null;

	BaseStore<BusiObject> get_g_Store() {
		if (g_store == null) {
			create_g_Store();
		}
		return g_store;
	}

	BaseStore<BusiObject> create_g_Store() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("upicode");
		type.getField("upicode").setType(Long.class);
		type.addField("codename");
		type.getField("codename").setType(String.class);
		type.addField("cgicode");
		type.getField("cgicode").setType(String.class);
		type.addField("cgcode");
		type.getField("cgcode").setType(String.class);
		type.addField("gcode");
		type.getField("gcode").setType(String.class);
		type.addField("modeltype");
		type.getField("modeltype").setType(String.class);
		type.addField("upric");
		type.getField("upric").setType(Double.class);
		type.addField("paytype");
		type.getField("paytype").setType(Integer.class);
		type.addField("qty");
		type.getField("qty").setType(Double.class);
		type.addField("qtyunit");
		type.addField("copybusicode");
		type.addField("copyicode");
		
		StoreInfo info = new StoreInfo();
		info.setTablename("paymentsg");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from paymentsg where upicode={icode}");
		 info.setParent(mstore);// 关联主表
		 info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		 info.setLinkparent_chile_columns(new String[] { "upicode" });//
		// 关联主表字段
		g_store = new BaseStore<BusiObject>(type, info);
		return g_store;
	}

	int sync = 0;                                                      
	Listener<BaseEvent> defaultlistener;                               
                                                                     
	Listener<BaseEvent> getListener() {                                
		if(defaultlistener!=null)                                        
		{                                                                
			return defaultlistener;                                        
		}                                                                
                                                                     
		defaultlistener = new Listener<BaseEvent>() {                    
			public void handleEvent(BaseEvent be) {                        
				sync++;                                                      
				try {                                                        
					if (sync == 1) {                                           
						if (be.getType() == Events.Select) {                     
							if (be.getSource().equals(addpayitem)) {
								
								addInvoice();
							}       
							
						}
						else if (be.getType() == Events.Hide) {    
							
						}
					
						else if(be.getType() == Events.Change)
						{
							if(be.getSource().equals(busistatus))
							{
								GWT.log("busistatus="+busistatus.getValue());
							}
							
						}
						else if (be.getType() == Events.KeyUp) {               
							if (be instanceof ComponentEvent) {                    
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{                                                    
								}                                                    
							}                                                      
						}                                                        
					}                                                          
				} finally {                                                  
					sync--;                                                    
				}                                                            
			}

		                                                       
                                                                     
		};                                                               
		return defaultlistener;                                          
	}
	protected void ratify()
	{
	
		
		if(BeforeRatify())
		{
			if(OnRatify())
			{
				AfterRatify();
			}
		}
	}
	/**
	 * 添加发票
	 */
	private void addInvoice()
	{
		   
//		 if(scode.getValue()==null)
//		 {
//			 Window.alert("请先选择“仓库”");
//			 return;
//		 }
		PaymenItemDialog gd = new PaymenItemDialog(paytype){
				public  void doposted(List<BusiObject> at) {
					
					for(BusiObject bo:at)
					{
						HashMap<String,Object> h = new HashMap<String,Object>();
						if(bo.get("cgicode")!=null)
						h.put("cgicode", bo.get("cgicode"));
						if(bo.get("cgcode")!=null)
						h.put("cgcode", bo.get("cgcode"));
						if(bo.get("gcode")!=null)
						h.put("gcode", bo.get("gcode"));
						if(bo.get("modeltype")!=null)
						h.put("modeltype", bo.get("modeltype"));
						h.put("qty", bo.get("qty")==null?0:Double.parseDouble(bo.get("qty").toString()));
						h.put("qtyunit", bo.get("qtyunit"));
						h.put("upric", bo.get("upric")==null?0:Double.parseDouble(bo.get("upric").toString()));
						//重要
					//h.put("paytype", paytype);
						h.put("copyicode", bo.get("upicode"));
						get_g_Store().add(h);
					//	gcodetip.setHtml("默认是该商品库存余额，请修改“数量”吧");
						
					//	gcodetip.el().blink(FxConfig.NONE);  
					}
					this.close();
				}
		 };
		 
		
		 gd.show();
		 
                                            
	
	}
	@Override
	public boolean AfterRatify() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean BeforeRatify() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean OnRatify() {
		this.mask("提交....");
		int index = mstore.getCurcowindex();
		String icode = mstore.getValue(index, "icode").toString();
		//store._trySave(index);
		String sql = "update payments set busistatus='131072' where icode ='"
				+ icode + "' ";
		CommandSyncContainer list = new CommandSyncContainer();
		CommandSyncsql commandsql = new CommandSyncsql();
		//CommandPrepareCall commandpc = new CommandPrepareCall();
		
		commandsql.getV().addAll(mstore._trySave(index));
		commandsql.getV().add(sql);
		commandsql.setContinueorrollback(false);
		
		
		

		list.add(commandsql);
		
		
//		CommandSyncCopyUP cu = new CommandSyncCopyUP();
//		cu.setIcode(icode);
//		
//		list.add(cu);

		final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.SendCommandSync(list,
				this);
		
	
		
		//store.trySave(index);
		return true;
	}
	
	@Override
	public void onFailure(Throwable caught) {
		MessageBox.alert("错误", "网络出现连接失败！请重新提交。"+caught.getMessage(), null);
		this.unmask();// 提交的时候mask，现在取消mask
		
	}
	@Override
	public void onSuccess(CommandSyncReturnObject cyro) {
		if(cyro.isB())
		{
			mstore.setValue("busistatus", "131072");
			mstore.commitChanges();
			Info.display("", "提交成功");
		
		}
		else
		{
			MessageBox.alert("错误", cyro.getMessage(), null);
		}
		this.unmask();// 提交的时候mask，现在取消mask
		
	}   	

}
